package com.fbs.service.impl;

import com.fbs.dao.BookStockDao;
import com.fbs.entity.BookStock;
import com.fbs.service.BookStockService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class BookStockServiceImpl implements BookStockService {
    @Autowired
    private BookStockDao bookStockDao;
    @Autowired
    private RedissonClient redissonClient;
    @Override
    public String buyByIsbn(String isbn) {

        //synchronized (BookStockServiceImpl.class){
        RLock lock = redissonClient.getLock("isbn::" + isbn);
        lock.lock(30,TimeUnit.SECONDS);
        try {


            BookStock bookStock = bookStockDao.selectById(isbn);
            if (bookStock.getStock() > 0){
                bookStock.setStock(bookStock.getStock()-1);
                bookStockDao.updateById(bookStock);
                System.out.println("书的isbn编号为"+isbn+"商品剩余"+bookStock.getStock()+"本");
                return "书的isbn编号为"+isbn+"书本剩余"+bookStock.getStock()+"本";
            }else {
                System.out.println("isbn编号为"+isbn+"库存不足");
                return "isbn编号为"+isbn+"库存不足";
            }
        }finally {
            lock.unlock();
        }

        // }
    }
}
